package com.ckerchina.admin.ckadmin.service;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ckerchina.admin.ckadmin.cache.MemcachedService;
import com.ckerchina.admin.ckadmin.dao.SmsLogDAO;
import com.ckerchina.admin.ckadmin.domain.SmsLog;
import com.ckerchina.admin.ckadmin.service.sms.SMSServiceProvider;
import com.ckerchina.admin.ckadmin.service.sms.dto.SmsSendResult;

@Service
public class SMSService {

	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private SmsLogDAO smsLogDAO;
	@Value("${sms.send}")
	private Boolean smsSend;
	@Autowired
	private Map<String, SMSServiceProvider> providers = new HashMap<String, SMSServiceProvider>();

    @Autowired
    MemcachedService memcachedService;

	public SmsSendResult sendValidateMessage(String mobile){
        int code = new Random().nextInt(10000);
        DecimalFormat decimalFormat = new DecimalFormat("0000");
        String result = decimalFormat.format(code);
        memcachedService.set(mobile,60,result);
        return  sendMessage("progroupSmsProvider",mobile,result);
    }

    public boolean validateCode(String mobile,String code){
        String result  = memcachedService.get(mobile);
        if(code.equals(result)){
            return true;
        }
        return false;
    }

	/**
	 * 发送短信，并创建短信发送日志
	 * 
	 * @param channelName 短信发送渠道
	 * @param mobiles 短信号码，多个号码使用英文逗号分隔
	 * @param content 短信内容
	 * @return
	 */
	public SmsSendResult sendMessage(String channelName, String mobiles, String content) {
		logger.info("发送短信 channelName:{} mobileIds:{} text:{}", channelName, mobiles, content);
		if (!smsSend) {
			logger.info("smsSend={}设置为不发送短信", smsSend);
			return null;
		}
		if (StringUtils.isEmpty(channelName) || StringUtils.isEmpty(mobiles) || StringUtils.isEmpty(content)) {
			return null;
		}
		SMSServiceProvider provider = providers.get(channelName);
		if (provider == null) {
			return null;
		}
		SmsSendResult result = provider.sendMessage(mobiles, content);
		if (result.isSuccess()) {
			SmsLog smsLog = new SmsLog();
			smsLog.setChannelName(channelName);
			smsLog.setContent(content);
			smsLog.setMobiles(mobiles);
			smsLog.setCreateTime(new Date());
			smsLog.setResult(result.getResult());
			smsLog.setSmscount(smsLog.computeSmsCount());
			smsLogDAO.persist(smsLog);
		}
		return result;
	}

	public SmsSendResult sendVms(String channelName, String mobiles, String content) {
		logger.info("发送语音验证码 channelName:{} mobileIds:{} text:{}", channelName, mobiles, content);
		/*if (!smsSend) {
			logger.info("smsSend={}设置为不发送短信", smsSend);
			return null;
		}*/
		if (StringUtils.isEmpty(channelName) || StringUtils.isEmpty(mobiles) || StringUtils.isEmpty(content)) {
			return null;
		}
		SMSServiceProvider provider = providers.get(channelName);
		if (provider == null) {
			return null;
		}
		SmsSendResult result = provider.sendVMS(mobiles, content);
		if (result != null && result.isSuccess()) {
			SmsLog smsLog = new SmsLog();
			smsLog.setChannelName(channelName);
			smsLog.setContent(content);
			smsLog.setMobiles(mobiles);
			smsLog.setCreateTime(new Date());
			smsLog.setResult(result.getResult());
			smsLog.setSmscount(smsLog.computeSmsCount());
			smsLogDAO.persist(smsLog);
		}
		return result;
	}

	public Integer queryBalance(String channelName) {
		if (StringUtils.isEmpty(channelName)) {
			return null;
		}
		SMSServiceProvider provider = providers.get(channelName);
		if (provider == null) {
			return null;
		}
		return provider.queryBalance();
	}
}
